#include "Snake.h"

#include <string.h>
#include <math.h>

//------------------------------------------------------------------------------

Snake::Snake() {
	length = 5;
	tail = new Direction[length];

	moveDirection = R;

	x = 12;
	y = 12;
}

//------------------------------------------------------------------------------

Snake::~Snake() {
	delete[] tail;
}

//------------------------------------------------------------------------------

void Snake::setDirection( Direction d ) {
	if( fabs(moveDirection - d) != 2 )
		moveDirection = d;
}

//------------------------------------------------------------------------------

Snake::Direction* Snake::getTail() const {
	return tail;
}

//------------------------------------------------------------------------------

int Snake::getLength() const {
	return length;
}

//------------------------------------------------------------------------------

int Snake::getX() const {
	return x;
}

//------------------------------------------------------------------------------

int Snake::getY() const {
	return y;
}

//------------------------------------------------------------------------------

void Snake::move() {
	memmove( tail+1, tail, (length - 1)*sizeof(Direction) );

	if( moveDirection == U ) {
		y--;
		tail[0] = D;
	} else if( moveDirection == D ) {
		y++;
		tail[0] = U;
	} else if( moveDirection == L ) {
		x--;
		tail[0] = R;
	} else if( moveDirection == R ) {
		x++;
		tail[0] = L;
	}

	if( x >= WIDTH ) {
		x = 0;
	} else if( x < 0 ) {
		x = WIDTH-1;
	}

	if( y >= HEIGHT ) {
		y = 0;
	} else if( y < 0 ) {
		y = HEIGHT-1;
	}
}

//------------------------------------------------------------------------------

void Snake::add() {
	length++;

	Direction* newTail = new Direction[length];
	memcpy( newTail, tail, (length-1)*sizeof(Direction) );
	newTail[length-1] = tail[length-2];

	delete[] tail;

	tail = newTail;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
